import 'exchange_card.dart';
import 'exchange_user.dart';

enum ExchangeRequestStatus {
  pending, // 待处理
  accepted, // 已接受
  rejected, // 已拒绝
  expired, // 已过期
}

class ExchangeRequest {
  final String id;
  final ExchangeUser requester; // 请求交换的用户
  final ExchangeCard requestedCard; // 请求换入的卡片
  final ExchangeCard offeredCard; // 提供换出的卡片
  final ExchangeRequestStatus status;
  final DateTime createTime;
  final DateTime? handleTime; // 处理时间

  ExchangeRequest({
    required this.id,
    required this.requester,
    required this.requestedCard,
    required this.offeredCard,
    required this.status,
    required this.createTime,
    this.handleTime,
  });

  factory ExchangeRequest.fromJson(Map<String, dynamic> json) {
    return ExchangeRequest(
      id: json['id'] as String,
      requester: ExchangeUser.fromJson(json['requester'] as Map<String, dynamic>),
      requestedCard: ExchangeCard.fromJson(json['requestedCard'] as Map<String, dynamic>),
      offeredCard: ExchangeCard.fromJson(json['offeredCard'] as Map<String, dynamic>),
      status: ExchangeRequestStatus.values.firstWhere(
        (e) => e.toString() == 'ExchangeRequestStatus.${json['status']}',
        orElse: () => ExchangeRequestStatus.pending,
      ),
      createTime: DateTime.parse(json['createTime'] as String),
      handleTime: json['handleTime'] != null 
          ? DateTime.parse(json['handleTime'] as String)
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'requester': requester.toJson(),
      'requestedCard': requestedCard.toJson(),
      'offeredCard': offeredCard.toJson(),
      'status': status.toString().split('.').last,
      'createTime': createTime.toIso8601String(),
      'handleTime': handleTime?.toIso8601String(),
    };
  }
} 